import { t } from 'i18next'
import React, { useEffect, useMemo, useState } from 'react'
import { Wrap } from './style'
import { StyledBottom, IconNotFound, ErrorTips } from '../../style'
import { Card } from './card'
import { translatorCard, ICard, transHttpUrl } from './translator'
import { meetingStatus } from '@/api/global/interface'
import { useRequest } from 'ahooks'
import { fetchGetVrsAddress, fetchGetVrsProgram, IMeetingInfo } from '@/api/meetingSpace'
import { useGlobalStore } from '@/store/global'
/** 会议录像 */
const Record = ({ meetingInfo }: { meetingInfo: IMeetingInfo }) => {
	const user = useGlobalStore((state) => state.user)
	const vrsAuth = useMemo(
		() => ({
			play: user?.enable_play ? true : false,
			download: user?.enable_download ? true : false,
		}),
		[user]
	)
	const [list, setList] = useState<ICard[] | null>(null)
	const [vrsAddress, setVrsAddress] = useState<string>('')
	const [token, setToken] = useState<string>('')
	const { loading, data: dataVrs } = useRequest(fetchGetVrsAddress)
	useEffect(() => {
		if (!loading) {
			if (dataVrs && dataVrs.success && dataVrs.data) {
				fetchGetVrsProgram(transHttpUrl(dataVrs.data.address || ''), {
					sso_token: dataVrs.data.token,
					meetingmoid: meetingInfo.meetingMoid,
					prgs1page: 10000,
				})
					.then((data) => {
						if (data && data.success && data.prginfo) {
							setVrsAddress(dataVrs.data.address)
							setToken(dataVrs.data.token)
							const list = data.prginfo.map((x) =>
								translatorCard(x, {
									token: dataVrs.data.token,
									vrsAddress: transHttpUrl(dataVrs.data.address),
								})
							)
							setList(list)
						} else {
							setList([])
						}
					})
					.catch(() => {
						setList([])
					})
			} else {
				setList([])
			}
		}
	}, [dataVrs, user, loading, meetingInfo])
	return (
		<Wrap>
			{vrsAuth.play ? (
				list ? (
					<>
						{list.length > 0 &&
							list.map((val) => (
								<Card
									data={val}
									token={token}
									vrsAddress={transHttpUrl(vrsAddress)}
									key={val.programId}
									auth={vrsAuth}
								/>
							))}
						{list.length === 0 && (
							<ErrorTips>
								<IconNotFound />
								{meetingInfo.status === meetingStatus.END
									? t('会议中未开启会议录像')
									: t('暂无会议录像')}
							</ErrorTips>
						)}
					</>
				) : (
					<></>
				)
			) : (
				<ErrorTips>
					<IconNotFound />
					{t('无相关权限，无法查看会议录像')}。
				</ErrorTips>
			)}
			<StyledBottom />
		</Wrap>
	)
}
export default Record
